package com.wangsb.exception;


import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.invoke.MethodHandle;

/**
 * @Description: TODO
 * @author: shenbing.wang@hand-china
 * @date: 2021年02月24日 22:47
 */
@ControllerAdvice
public class GeneralExceptionHandle {

    @ExceptionHandler({Exception.class})
    public ModelAndView handleException(Exception exception) {
        System.out.println("全局异常处理");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("ex", exception);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);
        System.out.println(sw.toString());
        return modelAndView;
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ModelAndView handleException2(HttpServletResponse response, HttpServletRequest request, Exception exception, HandlerMethod handle) {
        int accept = request.getHeader("Accept").indexOf("application/json");
        System.out.println("accept = " + accept);
        if (request.getHeader("Accept").indexOf("application/json") > -1) {
            System.out.println();
            ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
            modelAndView.addObject("ex", exception.getMessage());
            modelAndView.addObject("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
            return modelAndView;
        }

        System.out.println("全局MissingServletRequestParameterException异常处理");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("ex", exception);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);
        System.out.println(sw.toString());
        return modelAndView;
    }
}
